// we need to bootstrap main applications here. Page need to provide a context. such as module name here.
define(['jquery', 'mustache',
        'module/template/homeTemplate'],
    function($, Mustache, template ) {
        var update = function(update){

            var totalCount=0;
            $.each(update.poll_data.options, function(index, item){
                totalCount= totalCount + item.resp_count;
                item.index = index;
            });

            update.totalResCount = totalCount;

            update.resExists = totalCount > 0;
            $.each(update.poll_data.options, function(index, item){
                item.percentage = (item.resp_count/totalCount)*100;
            });

            update.responder = update.responder !=null;
            update.response_title  =  update.response != null ? update.poll_data.options[update.response].title : '';
            // prepare template for update.
            var html = $(Mustache.to_html(template['vote-item'], update));


            function removeUpdate(){

            }

            if (update.mine && $.empty(update.comments)()) {
                html.find('a.js_remove_update').click(function () {
                    $.ajax({
                        url: '/user/deleteUpdate',
                        method: 'POST',
                        data: {updateId: update.upid}
                    }).done(function () {
                        html.remove();
                        // update module factory
                    }).fail(function () {
                        alert('oops ..');
                    });
                });
            } else {
                html.find('a.js_remove_update').remove();
            }

            var detailClick =  function(){
                $.getJSON('/user/getPollResponses?updateId='+$(this).data('update')).
                    done(function(data){

                        // process.
                        $.each(data, function(index, item){
                            item.selectedItem =  item.poll_data.options[item.agenda_option].title
                        });


                        var detail =  $(Mustache.render(template['vote-responseItem'], {response : data}));
                        html.find('.detailDiv').append( detail);
                        html.find('.detailDiv a').off('click');
                        html.find('.detailDiv a').once('click', function(){
                            detail.remove();
                            html.find('.detailDiv a').off('click');
                            html.find('.detailDiv a').once('click',detailClick);
                        });
                    })
            };

            html.find('a.resdetail').once('click',detailClick);


            html.find('input[type="radio"]').once('click', selectRadio);

            if(update.responder){
                html.find('ul.question li').hide();
                html.find('ul.question li.thankyou').css('display','block');
                html.find('.thankyou .change').show();
                changeEvent(update.response);
            }





            function cancel(anchor){
                html.find('.thankyou').show();
                html.find('.comment').hide();
                html.find('.commentTxt').show();
                anchor.show();
            }

            function showComment(comment, data){
                html.find('.comment').hide();
                html.find('.commentTxt blockquote').html(comment);
                html.find('.commentTxt').show();
                html.find('.commentTxt').find('a.edit').once('click', function(){
                    edit(data, comment);
                });
            }

            function submit(data){
                if($('.comment textarea').val().trim().length == 0){
                    alert('please write something.');
                    return;
                }
                $.ajax({
                    url : '/user/saveComment',
                    type : "POST",
                    data : {
                        txt : $('.comment textarea').val(),
                        responseID :  data.responseID
                    }}).done(function(){

                    html.find('.thankyou').show();
                    showComment($(".comment textarea").val());

                }).fail(function(){
                    alert('oops ..');
                });
            }

            function edit(data, commentTxt){
                html.find('.comment').show();
                html.find('.comment textarea').val(commentTxt);

                var anchor = $(this).hide();
                html.find('.commentTxt').hide();


                $('.comment .cancel').once('click', function(){
                    cancel(anchor);
                });

                $('.comment .submit').once('click', function(){
                    submit(data)
                });
            }

            function commentEvent(data){
                html.find('.thankyou').find('a.fileComment').once('click',  function (){
                    html.find('.thankyou').show();
                    html.find('.comment').show();
                    var anchor = $(this).hide();


                    $('.comment .cancel').once('click', function(){
                        cancel(anchor);
                    });

                    $('.comment .submit').once('click', function(){
                        submit(data);
                    });
                });
            }

            if(!update.response_comment){
                commentEvent({responseID : update.response_id  });
            } else {
                showComment(update.response_comment, {responseID : update.response_id  });
                html.find('.fileComment').hide();
            }

            function changeEvent(response){

                html.find('.thankyou').find('a.change').once('click',  function (){
                    html.find('.thankyou .message').hide();
                    var anchor = $(this).hide();
                    html.find('ul.question li.option').show();
                    $.each(html.find('ul.question li.option'), function(index, li){
                        if(index === response)
                            $(li).find('input').prop( "checked", true );
                    });
                });
            }


            function selectRadio(){

                var resposeNo = $(this).data('number'), updateId = $(this).data('updateid');
                //savePollResponse($response_number, $responder, $responseComment, $updateId)
               var ajaxObj =  {
                    url : '/user/response',
                    type : "POST",
                    data : {
                        updateId : updateId,
                        responseNo :  resposeNo
                    }
                };


                $.ajax(ajaxObj).done(function(data) {
                    html.find('ul.question li').hide();
                    html.find('.thankyou').show();

                    html.find('.thankyou').find('.js_response').html(update.poll_data.options[resposeNo].title);

                    html.find('.thankyou .message').show();
                    html.find('.thankyou .change').show();
                    commentEvent(data);
                    changeEvent();

                    // update module factory
                }).fail(function() {
                    alert('oops ..');
                });

            }



            return html;
        };
        return update;
    });
